package com.ocean.everyday.d001_countnicepairsinanarray;

import java.util.HashMap;
import java.util.Map;

/**
 * 寻找好的坐标对
 * https://leetcode.cn/problems/count-nice-pairs-in-an-array/
 * <p>
 * 输入：nums = [42,11,1,97]
 * 输出：2
 * 解释：两个坐标对为：
 * - (0,3)：42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121 。
 * - (1,2)：11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12 。
 * <p>
 * 输入：nums = [13,10,35,24,76]
 * 输出：4
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2023/01/17 <br>
 */
public class CountNicePairsInAnArray3 {
    public static void main(String[] args) {
        CountNicePairsInAnArray3 countNicePairsInAnArray = new CountNicePairsInAnArray3();
        int[] nums = {42, 11, 1, 97};
        int res = countNicePairsInAnArray.countNicePairs(nums);
        System.out.println(res);
        int[] nums2 = {13, 10, 35, 24, 76};
        res = countNicePairsInAnArray.countNicePairs(nums2);
        System.out.println(res);
    }

    /**
     * nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
     * 设f(i) = num[i] - rev(num[i])
     * <p>
     * 原表达式则有 f(i) = f(j)
     * 问题转变为统计 num[i] - rev(num[i]) 相同的 nums中的元素个数
     *
     * @param nums
     * @return
     */
    public int countNicePairs(int[] nums) {
        int res = 0;
        int MOD = 100000007;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int item = nums[i];
            int rev = rev(item);
            res = (res + map.getOrDefault(item - rev, 0)) % MOD;
            map.put(item - rev, map.getOrDefault(item - rev, 0) + 1);
        }
        return res;
    }


    private int rev(int ele) {
        int temp = ele;
        int j = 0;
        while (temp > 0) {
            j = j * 10 + temp % 10;
            temp = temp / 10;
        }
        return j;
    }

}
